<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\IndexApi;
use App\Model\AdminOrder;
use App\Model\Orderdetail;
use App\Model\HomeUserAddress;
use App\Http\Controllers\Home\ShopCartController;
use App\Http\Controllers\Home\ShowLinksController;
use DB;

class UserOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //从session中提取用户的基础信息
        $user = session('Homeuser-data');
        $notPay = AdminOrder::select('id', 'create_at', 'o_num', 'total', 'status', 'getname')
                                ->where([['user_id', $user['id']],
                                         ['status', 1]
                                         ])
                                ->orderBy('create_at', 'desc')
                                ->get();
        $notPayCount = count(AdminOrder::select('id')->where([['user_id', $user['id']],['status', 1]])->get());
        $notSend = AdminOrder::select('id', 'create_at', 'o_num', 'total', 'status', 'getname')
                                ->where([['user_id', $user['id']],
                                         ['status', 4]
                              ])
                                ->orderBy('create_at', 'desc')
                                ->get();
        $notSendCount = count(AdminOrder::select('id')->where([['user_id', $user['id']],['status', 4]])->get());
        $notGet = AdminOrder::select('id', 'create_at', 'o_num', 'total', 'status', 'getname')
                                ->where([['user_id', $user['id']],
                                         ['status', 5]
                              ])
                                ->orderBy('create_at', 'desc')
                                ->get();
        $notGetCount = count(AdminOrder::select('id')->where([['user_id', $user['id']],['status', 5]])->get());
        $over = AdminOrder::select('id', 'create_at', 'o_num', 'total', 'status', 'getname')
                                ->where([['user_id', $user['id']],
                                         ['status', 7]
                              ])
                                ->orderBy('create_at', 'desc')
                                ->get();
        $overCount = count(AdminOrder::select('id')->where([['user_id', $user['id']],['status', 7]])->get());
        $cancell = AdminOrder::select('id', 'create_at', 'o_num', 'total', 'status', 'getname')
                                ->where([['user_id', $user['id']]])
                                ->whereIn('status', [2, 3])
                                ->orderBy('create_at', 'desc')
                                ->get();
        $cancellCount = count(AdminOrder::select('id')->where([['user_id', $user['id']]])->whereIn('status', [2, 3])->get());
        $status = [1 => '未支付', 2 => '已取消', 3 => '支付超时，自动取消', 4 => '待发货', 5 => '待收货', 6 => '待评价', 7 => '交易完成', 8 => '用户已删除'];

        //查询站点信息
        $sate = IndexApi::getSate();

        //查询友情链接数据
        $link = new ShowLinksController;
        $linksArray = $link->index();

        return view('Home/goods-order_list', [
            'user' => $user,
            'notPay' => $notPay,
            'notSend' => $notSend,
            'notGet' => $notGet,
            'over'  => $over,
            'cancell' => $cancell,
            'orderStatus' => $status,
            'notPayCount' => $notPayCount,
            'notSendCount' => $notSendCount,
            'notGetCount' => $notGetCount,
            'overCount' => $overCount,
            'cancellCount' => $cancellCount,
            'sate' => $sate,
            'linksArray' => $linksArray,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     * 用户在前台个人中心的订单列表页面对未支付的订单进行立即支付
     * @param  \Illuminate\Http\Request  $request AJAX传递过来的订单id
     * @return \Illuminate\Http\Response 状态码，404表示支付失败，200支付成功
     */
    public function orderPay(Request $request)
    {
        //拿到oid
        $oid = $request->oid;
        $uid = session('Homeuser-data')['id'];

        //先检查订单状态，如果不是待支付状态就告诉用户结果
        $status = AdminOrder::select('status', 'o_num')
                            ->where('id', $oid)
                            ->first()
                            ->toArray();

        if ($status['status'] == 3) {
            echo "<script>alert('订单超时未支付，已自动取消')</script>";
            exit;
        } else if ($status['status'] == 1) {
            // 来到这里说明订单状态为未支付，根据传递过来oid去查询订单详情并并返回到支付视图
            $getMsg = HomeUserAddress::select('getname', 'phone', 'address', 'ssq')
            ->where('user_id', $uid)
            ->where('whether_address', 1)
            ->get()
            ->toArray();

            $orderDetails = DB::table('shop_order_details')
            ->select('gname', 'price', 'buynum')
            ->where('order_id', $oid)
            ->get()
            ->toArray();

            //获取这个订单的商品名和总价
            $names = '';
            $total = 0;//总价
            foreach ($orderDetails as $detail) {
                $names = $detail->gname.' / ';
                $total += $detail->price * $detail->buynum;
            }

            //获取购物车数量显示在购物车标志上
            $shopCartController = new ShopCartController;
            $originalNum = $shopCartController->showCartNumber();//购物车数量

            return view('Home.goods-orderSuccess', [
                'getMsg' => $getMsg[0],
                'names' => $names,
                'o_num' => $status['o_num'],
                'totalPay' => $total,
                'orderId' => $oid,
                'originalNum' => $originalNum,
            ]);
            exit;
        } else if ($status['status'] > 3) {
            echo "<script>alert('订单已经支付过啦')</script>";
            return redirect()->route('orderlist');
            exit;
        }
    }

    /**
     * Display the specified resource.
     * 用户点击订单页的详情
     * @param  int  $id get传参oid
     * @return \Illuminate\Http\Response 返回详情数据到详情页面
     */
    public function orderDetail($oid)
    {
        $oid = intval($oid);

        // 先防止订单不存在和用户恶意查看别人的订单详情

        $uid = session('Homeuser-data')['id'];
        $res = AdminOrder::select('user_id')
                 ->where('id', $oid)
                 ->get()
                 ->toArray();

        if (!$res || $res[0]['user_id'] != $uid) {
            return redirect()->route('Home.index');
        }

        //走到这里说明订单和用户匹配
        $order = DB::table('shop_orders')
                   ->select('o_num', 'total', 'pay_at', 'send_at', 'getname', 'address', 'phone', 'status', 'message', 'id')
                   ->where('id', $oid)
                   ->get();

        $orderDetail = DB::table('shop_order_details')
                         ->select('gname', 'buynum', 'price', 'desc')
                         ->where('order_id', $oid)
                         ->get();

        // 运费
        $payment = 6;

        //查询站点信息
        $sate = IndexApi::getSate();

        //查询友情链接数据
        $link = new ShowLinksController;
        $linksArray = $link->index();

        return view('Home.goods-order_detail', ['order' => $order[0], 'orderDetail' => $orderDetail, 'payment' => $payment, 'sate' => $sate, 'linksArray' => $linksArray]);


    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     * 用户在订单界面对未支付的订单进行取消操作
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response 响应回状态码，200正常，404失败
     */
    public function orderCancel(Request $request)
    {
        $oid = intval($request->oid);
        $uid = session('Homeuser-data')['id'];

        //先检查订单状态，如果不是待支付状态就告诉用户结果
        $status = AdminOrder::select('status', 'o_num')
                            ->where('id', $oid)
                            ->first()
                            ->toArray();

        if (!$status) {
            return response()->json([
                'status' => 402,
                'msg' => '该订单不存在',
            ]);
        }

        if ($status['status'] == 3) {
            return response()->json([
                'status' => 403,
                'msg' => '订单已超时，自动取消',
            ]);
        }

        if ($status['status'] == 1) {
            // 来到这里就取消用户订单状态
            $res = DB::table('shop_orders')
                     ->where('id', $oid)
                     ->update(['status' => 2]);

            if (!$res) {
                return response()->json([
                    'status' => 404,
                    'msg' => '取消失败，练习管理员',
                ]);

            }

            return response()->json([
                'status' => 200,
                'msg' => '取消成功',
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     * 处理用户在订单列表删除已取消的订单
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function orderDel(Request $request)
    {
        $oid = intval($request->oid);
        $uid = session('Homeuser-data')['id'];

        // 先检查该UID和oid是否匹配，不能匹配说明oid被用户恶意乱输
        $res = AdminOrder::select('user_id')
                         ->where('id', $oid)
                         ->first()
                         ->toArray();

        if (!$res || $res['user_id'] != $uid) {
            return response()->json([
                'status' => 404,
                'msg' => '再捣蛋就拉黑！',
            ]);
        }

        //走到这里说明订单id和UID匹配得上，再判断该oid对应的状态是否是已取消或者超时取消
        $status = AdminOrder::select('status')
                            ->where('id', $oid)
                            ->first()
                            ->toArray();

        if ($status['status'] == 2 || $status['status'] == 3 || $status['status'] == 7) {
            $res = DB::table('shop_orders')
                     ->where('id', $oid)
                     ->update(['status' => 8]);

            if (!$res) {
                return response()->json([
                    'status' => 405,
                    'msg' => '删除异常，请联系管理员！',
                ]);
            }

            return response()->json([
                'status' => 200,
                'msg' => '删除成功！',
            ]);

        }

        return response()->json([
            'status' => 406,
            'msg' => '非取消或已完成状态， 不能删除!',
        ]);

    }

    public function confirmGet(Request $request)
    {
        $oid = intval($request->oid);
        $uid = session('Homeuser-data')['id'];

        // 先检查该UID和oid是否匹配，不能匹配说明oid被用户恶意乱输
        $res = AdminOrder::select('user_id')
                         ->where('id', $oid)
                         ->first()
                         ->toArray();

        if (!$res || $res['user_id'] != $uid) {
            return response()->json([
                'status' => 404,
                'msg' => '再捣蛋就拉黑！',
            ]);
        }

        $confirmMsg = DB::table('shop_orders')
                        ->where('id', $oid)
                        ->update(['status' => 7, 'over_at' => date('Y-m-d H:i:s')]);

        if (!$confirmMsg) {
            return response()->json([
                'status' => 403,
                'msg' => '收货失败，稍后再试',
            ]);
        }

        return response()->json([
            'status' => 200,
            'msg' => '收货成功！',
        ]);


    }

}
